package com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.PurOut;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.PutInStock;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.RfidCodebind;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.model.DaohuoList;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.model.ShangjiaList;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.service.RfidCodeDetailService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderNoticeEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.OrderNoticeService;
import com.yonyou.ucf.mdf.app.isvdxq.other.controller.PublicController;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.StorerecordEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpclistService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpcotherService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpcpickService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.StorerecordService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/rfidcodedetail",DxqConfig.pre_pcUrl+"/rfidcodedetail"})
public class RfidCodeDetailController {
    private static final Logger logger = LoggerFactory.getLogger(PublicController.class);

    @Autowired
    BaseService baseService;
    @Autowired
    private RfidCodeDetailService rfidCodeDetailService;
    @Autowired
    private OrderNoticeService orderNoticeService;
    @Autowired
    EpclistService epclistService;

    /**
     * @param tenant_id
     * @param orderid       单据ID，采购入库单ID
     * @param orderdetailid 单据详情ID，采购入库单详情ID
     * @param ordertype     单据类型：1采购入库单，2发货单 3到货单
     * @param shangjiatype  是否上架  空字符串:查所有标签  0未上架  1已上架
     * @return
     */
    //查询绑定的标签明细 shangjiatype 0未上架 1上架 ""所有
    @RequestMapping("/getReRFIDCodeDetail")
    public DataResult getReRFIDCodeDetail(String tenant_id, String orderid, String orderdetailid, String ordertype,
                                          String shangjiatype) {
        return rfidCodeDetailService.selectReRFIDCodeAll(orderid, orderdetailid, ordertype, shangjiatype, tenant_id);
    }

    //查询到货单上架 分配标签的状态 orderdetailid 逗号分隔
    @RequestMapping("/selectReRFIDStatusCount")
    public DataResult selectReRFIDStatusCount(String tenant_id, @RequestBody ShangjiaList shangjiaList) {
        return rfidCodeDetailService.selectReRFIDStatusCount(shangjiaList.getId(), tenant_id);
    }

    //查询发货单拣货 分配标签的状态 orderdetailid 逗号分隔
    @RequestMapping("/selFaRFIDStatusCount")
    public DataResult selFaRFIDStatusCount(String tenant_id, @RequestBody ShangjiaList shangjiaList) {
        return rfidCodeDetailService.selFaRFIDStatusCount(shangjiaList.getId(), tenant_id);
    }

    /**
     * 查询返回出库单拣货信息
     * 返回库存状态 4已拣货，5已配货 数据列表
     * @param tenant_id
     * @param orderid
     * @return
     */
    @RequestMapping("/getPickingDetail")
    public DataResult getPickingDetail(String tenant_id, String orderid) {
        return rfidCodeDetailService.selectPickingDetail(orderid, tenant_id);
    }

    /**
     * 拣货根据物资id和物资skuid获取当前货架信息
     *
     * @param tenant_id
     * @param product_id
     * @param product_sku_id
     * @param warehouse_id
     * @param batchno        出货批次
     * @param count          出货数量
     * @return
     */
    @RequestMapping("/GetlocaltionH")
    public DataResult GetlocaltionH(String tenant_id, String product_id, String product_sku_id, String warehouse_id,
                                    String batchno, String count) {
        return rfidCodeDetailService.GetlocaltionH(product_id, product_sku_id, warehouse_id, batchno, count, tenant_id);
    }

    //获取到货单的分配标签信息
    @RequestMapping("/getDaohuoListHcount")
    public DataResult getDaohuoDetailCount(String tenant_id, String orderid, String userId) {
        return rfidCodeDetailService.getDaohuoDetailCount(orderid, tenant_id, userId);
    }

    @Autowired
    private EpcpickService epcpickService;

    //手持机推送接口到用友，用友会写本地数据 [===入库回写]
    @RequestMapping("/UpdateInStockParams")
    public DataResult UpdateInStockParams(HttpServletRequest request, @RequestBody Map<String, Object> paramData) throws Exception {
        DataResult result = new DataResult(0, "操作失败");
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        Map<String, Object> myParms = RequestTool.getParams(request);
        String batch_no = (String) myParms.get("batch_no");
        String recordlistString = JSONObject.toJSONString(paramData.get("recordlist"));
        String putinstocklistString = JSONObject.toJSONString(paramData.get("putinstocklist"));
        List<DaohuoList> recordlist = JSONArray.parseArray(recordlistString, DaohuoList.class);
        List<PutInStock> putinstocklist = JSONArray.parseArray(putinstocklistString, PutInStock.class);
        List<String> epcids = new ArrayList<>();
        List<String> recordids = new ArrayList<>();
        if (recordlist == null || recordlist.size() == 0) return result;
        recordids = recordlist.stream().map(it -> it.getRecordid()).distinct().collect(Collectors.toList());
        if (recordids.size() == 0)
            epcids = recordlist.stream().map(it -> it.getId()).distinct().collect(Collectors.toList());
        result = epcpickService.InStockParamsCallback(putinstocklist, epcids, recordids, tenantId, batch_no);
        if (result.getStatus() != 1) {
            try {
                String modifier = putinstocklist.get(0).getModifier();
                String orderid = putinstocklist.get(0).getSourceid();
                String orderdetailid = putinstocklist.get(0).getOrderdetailid();
                String modelString = JSONObject.toJSONString(putinstocklist);
                OrderNoticeEntity recordEntity = new OrderNoticeEntity();
                recordEntity.setTenant_id(tenantId);
                recordEntity.setOrderid(orderid);
                recordEntity.setOrderdetailids(orderdetailid);
                recordEntity.setActioncode("callback");
                recordEntity.setType(DxqConfig.TypeFail); //本地回写失败
                recordEntity.setRemarkyonyou(modelString);
                recordEntity.setRemarkdxq(JSONObject.toJSONString(recordlist));
                recordEntity.setRemark(result.getMessage());
                recordEntity.setModifier(modifier);
                recordEntity.setStatus(result.getStatus());
                orderNoticeService.InsertEntity(recordEntity);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
            result.setMessage("本地回写失败");
            result.setStatus(1);
        }
        return result;
    }

    /**
     * 更新拣货信息为出库 [===出库回写]
     * todo 验证手持是否支持 用友可能不限制（超单发货）多次提交
     *
     * @param request
     * @param PurOutList
     * @return
     */
    @RequestMapping("/UpdateOutStatus")
    public DataResult UpdateOutStatus(HttpServletRequest request, @RequestBody List<PurOut> PurOutList) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, Object> reqParams = RequestTool.getParams(request);
            String orderid = (String) reqParams.get("orderid");
            String orderdetailid = (String) reqParams.get("orderdetailid");
            String pickbatchno = (String) reqParams.get("pickbatchno"); //配货编号
            System.out.println(JSONObject.toJSONString(reqParams));
            System.out.println(orderid + "|" + pickbatchno);
            if (StringUtils.isEmpty(orderid) || StringUtils.isEmpty(pickbatchno)) {
                result.setMessage("参数异常");
                return result;
            }
            result = epcpickService.OutStatusCallback(PurOutList, orderid, pickbatchno, tenantId, userId);
            if (result.getStatus() != 1) {
                orderNoticeService.EditEntityStatusForPick(orderid, DxqConfig.AllotOk, 1, DxqConfig.StatusFail, userId, pickbatchno, tenantId);
                try {
                    String modelString = JSONObject.toJSONString(PurOutList);
                    OrderNoticeEntity recordEntity = new OrderNoticeEntity();
                    recordEntity.setTenant_id(tenantId);
                    recordEntity.setOrderid(orderid);
                    recordEntity.setOrderdetailids(orderdetailid);
                    recordEntity.setActioncode("callback");
                    recordEntity.setPickbatchno(pickbatchno);
                    recordEntity.setType(DxqConfig.TypeFail); //本地回写失败
                    recordEntity.setRemarkyonyou(modelString);
                    recordEntity.setRemarkdxq("");
                    recordEntity.setRemark(result.getMessage());
                    recordEntity.setModifier(userId);
                    recordEntity.setStatus(result.getStatus());
                    orderNoticeService.InsertEntity(recordEntity);
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
                result.setMessage("本地回写失败");
                result.setStatus(1);
            }
        } catch (Exception ex) {
            String logtxt = "[OutStatusCallback]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }

    @Autowired
    StorerecordService storerecordService;

    //根据单子主键， 详情表主键绑定标签 [===发签入库]
    @PostMapping("/SubmitBindReRFIDCode")
    public DataResult SubmitBindReRFIDCode(@RequestBody List<RfidCodebind> CodeBindList, HttpServletRequest request) throws IOException {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            List<String> epcs = CodeBindList.stream().map(it -> it.getRfid_code()).distinct().collect(Collectors.toList());
            List<EpcEntity> list_epcEntity = epclistService.SelectByEpcs(epcs, tenantId);
            boolean flagEpcUsed = EpcotherService.CheckEpcUsed(list_epcEntity);
            if (flagEpcUsed) {
                result.setMessage("标签已占用");
                return result;
            }
            String ordertype = CodeBindList.get(0).getOrdertype();
            String orderid = CodeBindList.get(0).getOrderid();
            if (StringUtils.isEmpty(orderid) || StringUtils.isEmpty(ordertype)) {
                result.setMessage("数据异常，必须有单号和单据类型");
                return result;
            }
            List<StorerecordEntity> daohuoList = storerecordService.getDaohuoList(orderid, tenantId, userId);
            String pickbatchno = "";//私有接受批次
            if (daohuoList == null || daohuoList.size() == 0) pickbatchno = MyTool.GenerateBatchnoDXQ(ordertype);
            else pickbatchno = daohuoList.get(0).getBatchno_dxq();

            String batchNum = MyTool.GenerateBatchnoDXQ(ordertype);//私有发签批次
            result = rfidCodeDetailService.BindRfidCode(CodeBindList, batchNum, pickbatchno);
            result.setData(pickbatchno);
        } catch (Exception ex) {
            String logtxt = "[SubmitBindReRFIDCode]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }

    //拣货 [===发货出库]
    @PostMapping("/FahuoRFIDCode")
    public DataResult FahuoRFIDCode(String tenant_id, @RequestBody List<PurOut> PurOutList) {
//        return rfidCodeDetailService.FahuoRFIDCode(PurOutList, tenant_id);
        DataResult result = new DataResult(0, "操作失败");
        try {
            result = epcpickService.EpcpickSubmit(PurOutList, tenant_id);
        } catch (Exception ex) {
            String logtxt = "[FahuoRFIDCode]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }

    //删除拣货
    @RequestMapping("/DelJianhuo")
    public DataResult DelJianhuo(String tenant_id, String id, String rfidcodeId, String modifier) {
        return rfidCodeDetailService.DelJianhuo(id, rfidcodeId, modifier, tenant_id);
    }

    //获取库存数量
    @RequestMapping("/GetKucunCount")
    public DataResult GetKucunCount(String tenant_id, String product_id, String product_sku_id, String warehouse_id) {
        return rfidCodeDetailService.GetKucunCount(product_id, product_sku_id, warehouse_id, tenant_id);
    }

    //根据单子主键， 详情表主键解绑标签 默认到货发签解绑
    @RequestMapping("/JieBindReRFIDCode")
    public DataResult JieBindReRFIDCode(String tenant_id, String id, String modifier) {
        return rfidCodeDetailService.JieBindRfidCode(id, modifier, tenant_id);
    }

    //根据单子主键， 下架标签的货位信息
    @RequestMapping("/CleanBindReRFIDCode")
    public DataResult CleanBindReRFIDCode(String tenant_id, String id, String modifier) {
        return rfidCodeDetailService.CleanReRFIDCode(id, modifier, tenant_id);
    }

    /**根据单子主键， 上架货品标签的货位信息
     * [EPC 上架] 入库物资上架，修改货位和物资库存状态
     * @param tenant_id
     * @param shangjiaList
     * @return
     * @throws Exception
     */
    @PostMapping("/ShangjiadReRFIDCode")
    public DataResult ShangjiaCode(String tenant_id, @RequestBody ShangjiaList shangjiaList) throws Exception {
        logger.info("上架参数+++++++++++:id:" + shangjiaList.getId() + " Localid:" + shangjiaList.getLocationId() +
                "Modifier:" + shangjiaList.getModifier() + "租户id:" + tenant_id);
        DataResult result = new DataResult(0, "操作失败");
        try {
            String ordertype = "3";//到货单标签上架
            List<String> ids = Arrays.asList(shangjiaList.getId().split(",")).stream().filter(it -> !it.isEmpty()).distinct().collect(Collectors.toList());
            String epcIds = String.join(",", ids);
            result = rfidCodeDetailService.EditEpcForShangjia(epcIds, shangjiaList.getLocationId(), ordertype, shangjiaList.getModifier(), tenant_id);
        } catch (Exception ex) {
            String logtxt = "[ShangjiadReRFIDCode]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }


    /**
     * 查询标签是否被占用接口
     *
     * @param RfidCode rfidcode
     * @return 返回是否被占用查询结果
     */
    @RequestMapping("/checkRfidOccupy")
    public DataResult checkRfidOccupy(String tenant_id, String RfidCode, String orderId, String ordertype) {
        DataResult dataResult = new DataResult();
        dataResult.setStatus(1);
        dataResult.setMessage("查找信息失败");
        try {
            return rfidCodeDetailService.checkRifdOccupy(RfidCode, orderId, ordertype, tenant_id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataResult;
    }
}
